package net.wicp.tams.duckula.server.connector;

import javax.management.remote.JMXConnector;

import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.common.others.DockerUtil;
import net.wicp.tams.commons.Conf;
import net.wicp.tams.commons.Result;
import net.wicp.tams.commons.apiext.JmxUtil;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.duckula.server.service.MBeanUtil;
import net.wicp.tams.duckula.server.service.ServerAssit;

@Service(value = "TaskStop")
@Slf4j
public class TaskStop implements IBusiApp {
	@Override
	public CusDynaBean exe(CusDynaBean inputBean, CusDynaBean outBeanOri) {
		long begintime = System.currentTimeMillis();
		String taskId = inputBean.getStrValueByName("taskId");
		String enableDocker = Conf.get("duckula.docker.enable");
		if (StringUtil.isNotNull(enableDocker) && "true".equals(enableDocker)) {// 走docker//
																				// 走docker
			String containerId = ServerAssit.findContainerId(taskId);
			try {
				DockerUtil.getInst().getDocker().stopContainer(containerId, 10);
				outBeanOri.setResult(Result.getSuc());
			} catch (Exception e) {
				log.error("停止docker失败", e);
				// TODO 返回结果
				outBeanOri.setResult(Result.getError(e.getMessage()));
			}
		} else {
			int jmxPort = Integer.parseInt(inputBean.getStrValueByName("jmxPort"));
			jmxPort = jmxPort > 0 ? jmxPort : StringUtil.buildPort(taskId);
			log.info("opt:stop,taskId:{},jmxPort:{}", taskId, jmxPort);
			JMXConnector conn = JmxUtil.connect(jmxPort);
			MBeanUtil.stopTask(conn);
			try {
				conn.close();
			} catch (Exception e) {
				// 都停了任务任务肯定抛异常
				// log.error("stop error", e);
			}
			outBeanOri.setResult(Result.getSuc());
		}
		outBeanOri.set("usetimes", String.valueOf(System.currentTimeMillis() - begintime));
		return outBeanOri;
	}
}
